import React, { useCallback, useState } from "react";
import { utils } from "elmer-common";
import { useForm } from "./Context";

interface IFormItem {
    children: React.ReactNode;
    name: string;
    defaultValue?: any;
}

const getElementDefaultProps = (target: any, defaultValue?: any) => {
    if(target.type === "input" && ["checkbox", "radio"].includes(target.props.type)) {
        return { defaultChecked: defaultValue };
    } else {
        return { defaultValue };
    }
};

export const FormItem = ({ children, name, defaultValue }: IFormItem) => {
    const form = useForm();console.log(form.defaultValues?.[name], name);
    const [ defaultValueData ] = useState(() => form.defaultValues?.[name] ?? defaultValue);
    const nextChildrenItem = utils.isArray(children) ? children : (
        children ? [children] : []
    );
    const onComponentChange = useCallback(() => {}, []);
    const onElementChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        if(event.target.type === "checkbox" || event.target.type === "radio") {
            form.set(name, event.target.checked);
        } else {
            form.set(name, event.target.value);
        }
    }, []);
    return (<>{
        nextChildrenItem.map((item, index) => {
            if(React.isValidElement(item)) {
                if(typeof item.type === "function") {
                    return React.cloneElement(item as any, {
                        key: index,
                        onChange: onComponentChange,
                        defaultValue: defaultValueData
                    });
                } else {
                    const defaultProps = getElementDefaultProps(item, defaultValueData);
                    // only input, checkbox, radio,
                    return React.cloneElement(item as any, {
                        key: index,
                        onChange: onElementChange,
                        ...defaultProps
                    });
                }
            } else {
                return <React.Fragment key={index}>{item}</React.Fragment>;
            }
        })
    }</>);
};
